﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MathLab.Messaging;

namespace MathLab.Utils
{
  class MatrixInverse
  {
    /// <summary>
    /// Creating an inverse matrix for given matrix
    /// </summary>
    /// <remarks>Could not create Inverse matrix for matrix which Determinant is equal zero</remarks>
    /// <param name="matrix"></param>
    /// <returns></returns>
    public static double[,] InverseMatrix(double[,] matrix)
    {
      if (MatrixCorrectness.IsSquaredMatrix(matrix))
      {
        if (0 == MatrixDet.Determinant(matrix))
        {
          throw new Exception("Could not create inverse Matrix: Determinant is 0");
        }

        double[,] matrixResult = new double[matrix.GetLength(0), matrix.GetLength(1)];

        for (int i = 0; i < matrix.GetLength(0); i++)
        {
          for (int j = 0; j < matrix.GetLength(1); j++)
          {
            matrixResult[j, i] = Math.Pow((-1), (i + j)) * MatrixDet.Determinant(MatrixDet.ComplementMatrix(matrix, i, j));
          }
        }
        return MatrixFactorMultiply.FactorMultiply(matrixResult, (1.0 / (MatrixDet.Determinant(matrix))));
      }
      else
      {
        throw new Exception("Could not create inverse matrix: Matrix is not squared");
      }
    }
  }
}
